/*
 * @Date: 2024-04-02 09:25:51
 * @LastEditors: bingkui.wu
 * @LastEditTime: 2024-04-07 09:32:46
 * @Description: 文字识别接口。传入图片文件，识别图片上的文字信息。
 */
import { REQUEST } from "#type/request";
import Response from "@common/Response";
import * as superagent from "superagent";
import { curTime } from "@common/utils";
import { getToken } from "@/serives/token";

/**
 * 获取文件base64编码
 * @param string  path 文件路径
 * @return string base64编码信息，不带文件头
 */
function getFileContentAsBase64(path: string) {
  const fs = require("fs");
  try {
    return fs.readFileSync(path, { encoding: "base64" });
  } catch (err) {
    throw new Error(err);
  }
}

const handwriting = (
  base64Data: string,
  detect_direction: string,
  token: string
) => {
  return new Promise((resolve, reject) => {
    const url = `https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token=${token}`;
    console.log(curTime(), "调动云接口:handwriting ocr");

    superagent
      .post(url)
      .set("Content-Type", "application/x-www-form-urlencoded")
      .set("Accept", "application/json")
      .send({
        image: base64Data,
        detect_direction: detect_direction,
        recognize_granularity: "big",
        probability: "false",
      })
      .end((err, res) => {
        if (err) {
          return reject(Response.Error(1001, err));
        }
        console.log(
          curTime(),
          "handwriting OCR res=",
          JSON.stringify(res.body)
        );
        const { words_result_num } = res.body;
        if (detect_direction === "true") {
          resolve(Response.Success(res.body));
        } else if (words_result_num === 0) {
          reject(Response.Error(1001, "没有识别到结果"));
        } else {
          resolve(Response.Success(res.body));
        }
        
      });
  });
};

const general_basic = (
  base64Data: string,
  detect_direction: string,
  token: string
) => {
  return new Promise((resolve, reject) => {
    const url = `https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=${token}`;
    console.log(curTime(), "调动云接口:general_basic ocr");

    superagent
      .post(url)
      .set("Content-Type", "application/x-www-form-urlencoded")
      .set("Accept", "application/json")
      .send({
        image: base64Data,
        language_type: "ENG",
        detect_direction: detect_direction,
        detect_language: "false",
        paragraph: "false",
        probability: "false",
      })
      .end((err, res) => {
        if (err) {
          return reject(Response.Error(1001, err));
        }
        resolve(Response.Success(res.body));
        console.log(
          curTime(),
          "general_basic OCR res=",
          JSON.stringify(res.body)
        );
      });
  });
};

const root: REQUEST.BASIC = {
  auth: false,
  method: "post",
  request: async (ctx: any) => {
    return new Promise(async (resolve, reject) => {
      const { files, fields } = ctx.request.body;
      const { detect_direction } = fields;
      const token = await getToken("TEXT");
      const { file } = files;

      console.log(curTime(), "OCR调用 file=", file.path, ", detect_direction=", detect_direction);
      // 读取文件
      // 将文件数据转换为Base64编码
      const base64Data = getFileContentAsBase64(file.path);

      handwriting(base64Data, detect_direction, token)
        .then(resolve)
        .catch((err) => {
          if (detect_direction === "true") {
            reject(err);
          } else {
            general_basic(base64Data, detect_direction, token).then(
              resolve,
              reject
            );
          }
        });
    });
  },
};

export default root;
